package com.hula.onion.book.server.spider.platforms.tuandai;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.DateUtils;
import com.hula.onion.book.server.utils.RSAUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:49
 *
 * @author liangbing
 * @version 1.0
 */
@Component
public class TuanDaiSpiderHelper {

    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form, String publicKey) throws Exception {

        Map<String, Object> map = new HashMap<>(6);

        map.put("un", RSAUtils.encryptBASE64(RSAUtils.encryptByPublicKey(form.getUserName(), publicKey)));
        map.put("pd", RSAUtils.encryptBASE64(RSAUtils.encryptByPublicKey(form.getPassword(), publicKey)));
        //loadType = 2 时不再弹出验证码
        map.put("loadType", "2");
        map.put("t", DateUtils.getCurrentMillisecond());
        map.put("encrypt", 1);
        map.put("ticket", form.getTicket());

        return map;

    }

    /**
     * 解析账户余额
     *
     * @param accountHtml
     * @param interestHtml
     * @return
     */
    public CommonResponse parseAccountBalance(String accountHtml, String interestHtml) {

        try {
            AccountInfo accountInfo = new AccountInfo();
            Document dc = Jsoup.parse(accountHtml);
            Element el = dc.selectFirst("div.account-data");
            String amount = el.getAllElements().get(7).text();
            String fAmount=StringUtils.remove(amount,",");
            accountInfo.setAmount(new BigDecimal(fAmount));
            dc = Jsoup.parse(interestHtml);
            String totalInterest = dc.selectFirst("#recAmount").text();
            String fTotalInterest=StringUtils.removePattern(totalInterest,"['￥',',']");
            accountInfo.setTotalIntrest(new BigDecimal(fTotalInterest));
            String waitInterest = dc.selectFirst("#dueAmount").text();
            String fWaitInterest=StringUtils.removePattern(waitInterest,"['￥']");
            accountInfo.setWaitIntrest(new BigDecimal(fWaitInterest));
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }
}
